package com.heima.admin.gateway.fliter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
@RefreshScope
public class AuthorizationFilter implements GlobalFilter{

    @Value("${ignoreUrl}")
    private List<String> ignoreUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取response和request对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.判断是否是登录,如果是，放行
        String path = request.getURI().getPath();
        log.info("请求路径为：{}",path);
        //放行代码
//        path = ignoreUrl.get(0);
//        if (ignoreUrl.contains(path)){
//            log.info("放行");
//            return chain.filter(exchange);
//        }
        if (true){
            return chain.filter(exchange);
        }
        //判断是否有token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            log.info("token为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int status = AppJwtUtil.verifyToken(claimsBody);
        if (status == 1 || status == 2){
            log.info("token已过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

//    @Override
//    public int getOrder() {
//        return -1;
//    }
}
